package hz.mobileproject.pda.toolsmanager.activity;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;

import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.ViewInject;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import hz.mobileproject.pda.R;
import hz.mobileproject.pda.app.MainApp;
import hz.mobileproject.pda.entity.request.Request_loadPoliceInfo;
import hz.mobileproject.pda.entity.response.Response_loadPoliceInfo;
import hz.mobileproject.pda.entity.response.Response_login_user;
import hz.mobileproject.pda.listener.CustomNetCallBack;
import hz.mobileproject.pda.network.Constance;
import hz.mobileproject.pda.toolsmanager.adapter.ToolsRecyclerWaitLVAdaper;
import hz.mobileproject.pda.toolsmanager.adapter.ToolsStockAdapter2;
import hz.mobileproject.pda.toolsmanager.adapter.WaiJieToolsAdapter;
import hz.mobileproject.pda.toolsmanager.bean.request.RQ_BorrowedTool;
import hz.mobileproject.pda.toolsmanager.bean.request.WaiJieToolBean;
import hz.mobileproject.pda.toolsmanager.bean.response.RP_FreeCountTools;
import hz.mobileproject.pda.toolsmanager.bean.response.RP_ToolInfo;
import hz.mobileproject.pda.toolsmanager.bean.response.RP_ToolSysSet;
import hz.mobileproject.pda.toolsmanager.utils.ToolCommonHttpUtils;
import hz.mobileproject.pda.ui.base.BaseScanActivity;
import hz.mobileproject.pda.utils.HttpRqUtils;
import hz.mobileproject.pda.utils.TextViewUtil;

@ContentView(R.layout.activity_wai_jie_tools)
public class WaiJieToolsActivity extends BaseScanActivity {

    @ViewInject(R.id.lv_tool_item)
    private ListView lv_tool_item;
    @ViewInject(R.id.tv_jc_person)
    private TextView tv_jy_person;
    @ViewInject(R.id.tv_jb_person)    //经办人
    private TextView tv_jb_person;
    @ViewInject(R.id.bt_end_waijie)
    private Button bt_end_waijie;
    //工具统计
    @ViewInject(R.id.lv_tools_stock)
    private ListView lv_tools_stock;

    private RP_ToolSysSet mToolSystemSet;
    private static final int REQUEST_CODE_POLICE = 0x1055;   //经办人
    private static final int REQUEST_CODE_PRISONER = 0x1056; //借用人
    private static final int REQUEST_CODE_TOOLS = 0x1057;    //外借工具
    //当前民警信息
    private Response_loadPoliceInfo mPoliceInfo;   //经办人信息
    //当前扫码民警
    private Response_loadPoliceInfo mJieYongPolice;   //借出人信息

    private Gson mGson;

    //外接工具 itemList
    private List<RP_ToolInfo> itemList = new ArrayList<>();
    //外接工具 adapter
    private WaiJieToolsAdapter addReportoryAdapter;
    private ToolsStockAdapter2 mToolsStockAdapter;
    private ToolsRecyclerWaitLVAdaper mWaitLVAdaper;




    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Override
    protected void initData() {
        setTitleText("外借工具");
        mGson = new Gson();


        addReportoryAdapter = new WaiJieToolsAdapter(WaiJieToolsActivity.this,itemList);
        lv_tool_item.setAdapter(addReportoryAdapter);


        mToolsStockAdapter = new ToolsStockAdapter2(this, new ArrayList<RP_FreeCountTools>());
        lv_tools_stock.setAdapter(mToolsStockAdapter);

        mToolSystemSet = (RP_ToolSysSet) getIntent().getSerializableExtra("key");
        //扫描民警
        scanPolice();

        bt_end_waijie.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                addBorowedToolToNet(addReportoryAdapter.getListData());
            }
        });


    }

    /**
     * 外接工具list请求
     * @param listData
     */
    private void addBorowedToolToNet(List<RP_ToolInfo> listData) {
        List<WaiJieToolBean> beans = new ArrayList<>();
        for(int i = 0; i < listData.size();i++) {
            RP_ToolInfo bean = listData.get(i);
            beans.add(new WaiJieToolBean(bean.getTool_id(),bean.getTool_name(),bean.getTool_type() + ""));

        }
        RQ_BorrowedTool tool = new RQ_BorrowedTool();
        tool.cus_number = mPoliceInfo.getCus_number() + "";
        tool.out_dprt_id = mPoliceInfo.getDepartment_id() + "";
        tool.out_dprt_name = mPoliceInfo.getDepartment_name();
        tool.out_person_id = mPoliceInfo.getPolice_id();
        tool.out_person_name = mPoliceInfo.getPolice_name();
        tool.in_dprt_id = mJieYongPolice.getDepartment_id() + "";
        tool.in_dprt_name = mJieYongPolice.getDepartment_name();
        tool.in_person_id = mJieYongPolice.getPolice_id();
        tool.in_person_name = mJieYongPolice.getPolice_name();
        tool.tool_data = beans;
        tool.borrow_time = TimeUtils.getNowString(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
        tool.status = 1 + "";   //外借   传2过去
        HttpRqUtils.httpPost(Constance.BASE_URL + Constance.URL_TOOL_BORROW_TOOL, tool, new CustomNetCallBack() {
            @Override
            public void onSuccessFromSer(int rtnCode, String rtnMsg, String data) {
                ToastUtils.showLong("外借成功");
                addReportoryAdapter.clearAll();
                getFreeToolsCountFromSer();
            }

            @Override
            public void onErrorFromSer(int rtnCode, String rtnMsg) {
                LogUtils.e(rtnMsg);
            }

            @Override
            public void onErrorFromNet(Throwable ex, boolean isOnCallback) {
                LogUtils.e(ex.toString());
            }
        });
    }

    @Override
    protected void onScanSucesess(int requestCode, String scanMsg) {
        LogUtils.e(scanMsg);
        switch (requestCode) {
            case REQUEST_CODE_POLICE:
                getPliceInfoFromSer(scanMsg);
                break;
            case REQUEST_CODE_PRISONER:   //扫描借用人
                getPrisonerInfoFromSer(scanMsg);
                break;

            case REQUEST_CODE_TOOLS:
                //TODO 扫描工具
                getToolInfoFromSer(scanMsg);
                break;
        }
    }

    /**
     * 请求网络接口获取库存信息
     */
    private void getFreeToolsCountFromSer() {
        ToolCommonHttpUtils.getFreeToolsCountFromSer(mPoliceInfo, new CustomNetCallBack() {
            @Override
            public void onSuccessFromSer(int rtnCode, String rtnMsg, String data) {
                LogUtils.e(data);
                List<RP_FreeCountTools> tempList = mGson.fromJson(data, new TypeToken<ArrayList<RP_FreeCountTools>>() {
                }.getType());
                mToolsStockAdapter.clearAdd(tempList);
                if (tempList == null || tempList.size() == 0) {
                    ToastUtils.showLong("库存信息为空");
                }
            }

            @Override
            public void onErrorFromSer(int rtnCode, String rtnMsg) {
                ToastUtils.showLong("获取库存信息失败(" + rtnCode + "," + rtnMsg + ")");
            }

            @Override
            public void onErrorFromNet(Throwable ex, boolean isOnCallback) {
                ToastUtils.showLong("获取库存信息失败");
                LogUtils.e(ex);
            }
        });
    }

    /**
     * 请求网络接口获取工具信息
     *
     * @param scanStr
     */
    private void getToolInfoFromSer(String scanStr) {
        ToolCommonHttpUtils.getToolInfoFromSer(scanStr,mToolSystemSet,mPoliceInfo, new CustomNetCallBack() {
            @Override
            public void onSuccessFromSer(int rtnCode, String rtnMsg, String data) {
                RP_ToolInfo toolInfo = mGson.fromJson(data, RP_ToolInfo.class);
                if (toolInfo == null) {
                    ToastUtils.showLong("工具信息格式错误或为空");
                    return;
                }


                //判断此工具是否已在外借列表
                for(int i = 0; i <itemList.size();i++) {
                    if(toolInfo.getTool_id().equals(itemList.get(i).getTool_id())) {
                        ToastUtils.showLong("此工具已存在列表中");
                        return;
                    }
                }
                //判断工具是否是借来的
                if(toolInfo.getBorrow_status() == RP_ToolInfo.BORROW_STATUS_ISBORROW) {
                    ToastUtils.showLong("此工具无法外借");
                    return;
                }
                addReportoryAdapter.add(toolInfo);

            }

            @Override
            public void onErrorFromSer(int rtnCode, String rtnMsg) {
                ToastUtils.showLong("获取工具信息失败(" + rtnCode + "," + rtnMsg + ")");
            }

            @Override
            public void onErrorFromNet(Throwable ex, boolean isOnCallback) {
                ToastUtils.showLong("获取工具信息失败");
                LogUtils.e(ex);
            }
        });
    }


    /**
     * 请求网络接口获取民警信息
     *
     * @param scanStr
     */
    private void getPliceInfoFromSer(String scanStr) {
        scanStr = scanStr.indexOf("P") == 0 ? scanStr.substring(1) : scanStr;
        Request_loadPoliceInfo rq_lpi = new Request_loadPoliceInfo();
        rq_lpi.setCusNumber(SPUtils.getInstance("app_login").getString(Constance.SP_CUSNUMBER));
        rq_lpi.setPoliceCode(scanStr);
        //发送获取民警信息接口请求
        HttpRqUtils.httpPost(Constance.BASE_URL + Constance.URL_LOAD_POLICE_INFO, rq_lpi, policeInfoCallback);
    }

    /**
     * 获取民警信息接口回调
     */
    private CustomNetCallBack policeInfoCallback = new CustomNetCallBack() {
        @Override
        public void onSuccessFromSer(int rtnCode, String rtnMsg, String data) {
            LogUtils.e(data);
            Response_loadPoliceInfo loadPoliceInfo = mGson.fromJson(data, Response_loadPoliceInfo.class);
            if (loadPoliceInfo == null) {
                ToastUtils.showLong("民警信息为空");
                return;
            }
            mScanLoadingDialog.dismiss();
            mPoliceInfo = loadPoliceInfo;
            TextViewUtil.setUnderLine(tv_jb_person,mPoliceInfo.getPolice_name());
            //接着扫描借出人条码
            scanAfterPolice();
        }

        @Override
        public void onErrorFromSer(int rtnCode, String rtnMsg) {
            ToastUtils.showLong("获取民警信息失败");
        }

        @Override
        public void onErrorFromNet(Throwable ex, boolean isOnCallback) {
            ToastUtils.showLong("获取民警信息失败");
            LogUtils.e(ex);
        }
    };


    /**
     * 请求网络接口获取借用人信息
     *
     * @param scanStr
     */
    private void getPrisonerInfoFromSer(String scanStr) {
        scanStr = scanStr.indexOf("P") == 0 ? scanStr.substring(1) : scanStr;
        Request_loadPoliceInfo rq_lpi = new Request_loadPoliceInfo();
        rq_lpi.setCusNumber(SPUtils.getInstance("app_login").getString(Constance.SP_CUSNUMBER));
        rq_lpi.setPoliceCode(scanStr);
        //发送借用人（民警）信息接口请求
        HttpRqUtils.httpPost(Constance.BASE_URL + Constance.URL_LOAD_POLICE_INFO, rq_lpi, prisonerInfoCallback);


    }

    /**
     * 获取民警信息接口回调
     */
    private CustomNetCallBack prisonerInfoCallback = new CustomNetCallBack() {
        @Override
        public void onSuccessFromSer(int rtnCode, String rtnMsg, String data) {
            LogUtils.e(data);
            Response_loadPoliceInfo loadPrisonerInfo = mGson.fromJson(data, Response_loadPoliceInfo.class);
            if (loadPrisonerInfo == null) {
                ToastUtils.showLong("借用人信息为空");
                return;
            }
            if(loadPrisonerInfo.getDepartment_id() == mPoliceInfo.getDepartment_id()) {
                ToastUtils.showLong("借用借出人部门相同");
                return;
            }
            mScanLoadingDialog.dismiss();
            mJieYongPolice = loadPrisonerInfo;
            TextViewUtil.setUnderLine(tv_jy_person,loadPrisonerInfo.getPolice_name());

            scanAfterPrison();

        }

        @Override
        public void onErrorFromSer(int rtnCode, String rtnMsg) {
            ToastUtils.showLong("获取民警信息失败");
        }

        @Override
        public void onErrorFromNet(Throwable ex, boolean isOnCallback) {
            ToastUtils.showLong("获取民警信息失败");
            LogUtils.e(ex);
        }
    };



    /**
     * ====================================扫描流程=========================================
     */
    private void scanPolice() {
        //是否需要扫描民警
        if (RP_ToolSysSet.TSS_CALL_TYPE_SCAN_USER == (mToolSystemSet.getCall_type())) {
            //扫民警
            openScan(REQUEST_CODE_POLICE, mToolSystemSet, "请扫描经办人民警条码");
        } else if (RP_ToolSysSet.TSS_CALL_TYPE_LOGIN_USER == (mToolSystemSet.getCall_type())) {
            //使用登录民警信息
            mPoliceInfo = new Response_loadPoliceInfo();
            Response_login_user loginUser = MainApp.getInstance().getLoginUser();
            mPoliceInfo.setCus_number(loginUser.getCus_number());
            mPoliceInfo.setDepartment_id(loginUser.getDepartment_id());
            mPoliceInfo.setDepartment_name(loginUser.getDepartment_name());
            mPoliceInfo.setPolice_code(loginUser.getPolice_code());
            mPoliceInfo.setPolice_id(loginUser.getPolice_id());
            mPoliceInfo.setPolice_name(loginUser.getPolice_name());
            TextViewUtil.setUnderLine(tv_jb_person,loginUser.getPolice_name());
            //接着扫描借出人条码
            scanAfterPolice();
        }
    }

    //使用登录民警为经办人，扫描借出人
    private void scanAfterPolice() {
        getFreeToolsCountFromSer();
        //扫描借出人
        openScan(REQUEST_CODE_PRISONER, mToolSystemSet, "请扫描借用人");
    }

    //扫描经办人后 扫描工具
    private void scanAfterPrison() {
        openScan(REQUEST_CODE_TOOLS, mToolSystemSet, "请扫描外借出工具");
    }


}
